import { NextRequest, NextResponse } from 'next/server';

// export const dynamic = 'force-static';

// 模拟用户数据
const users = [
  {
    id: 1,
    name: "张三",
    email: "zhangsan@example.com",
    role: "开发者",
    joinDate: "2024-01-01",
    avatar: "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100&h=100&fit=crop&crop=face"
  },
  {
    id: 2,
    name: "李四",
    email: "lisi@example.com",
    role: "设计师",
    joinDate: "2024-01-05",
    avatar: "https://images.unsplash.com/photo-1494790108755-2616b612b786?w=100&h=100&fit=crop&crop=face"
  },
  {
    id: 3,
    name: "王五",
    email: "wangwu@example.com",
    role: "产品经理",
    joinDate: "2024-01-10",
    avatar: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face"
  }
];

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const role = searchParams.get('role');

  let filteredUsers = users;

  // 按角色筛选
  if (role) {
    filteredUsers = filteredUsers.filter(user => 
      user.role.toLowerCase() === role.toLowerCase()
    );
  }

  // 模拟 API 延迟
  await new Promise(resolve => setTimeout(resolve, 150));

  return NextResponse.json({
    success: true,
    data: filteredUsers,
    count: filteredUsers.length,
    total: users.length
  });
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    // 验证必要字段
    if (!body.name || !body.email) {
      return NextResponse.json(
        { success: false, error: "姓名和邮箱是必填字段" },
        { status: 400 }
      );
    }

    // 检查邮箱是否已存在
    const existingUser = users.find(user => user.email === body.email);
    if (existingUser) {
      return NextResponse.json(
        { success: false, error: "该邮箱已被使用" },
        { status: 409 }
      );
    }

    // 创建新用户
    const newUser = {
      id: users.length + 1,
      name: body.name,
      email: body.email,
      role: body.role || "用户",
      joinDate: new Date().toISOString().split('T')[0],
      avatar: body.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(body.name)}&size=100`
    };

    // 模拟 API 延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    return NextResponse.json({
      success: true,
      data: newUser,
      message: "用户创建成功"
    }, { status: 201 });

  } catch {
    return NextResponse.json(
      { success: false, error: "请求格式错误" },
      { status: 400 }
    );
  }
}
